package site.kaede.dormctrlpanel;

import android.annotation.SuppressLint;
import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

public class MainActivity extends AppCompatActivity {

    private WebView webView;
    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 引用 WebView 和 SwipeRefreshLayout
        webView = findViewById(R.id.webview);
        swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);

        // 设置 WebViewClient，确保在 WebView 中打开链接
        webView.setWebViewClient(new WebViewClient());

        // 启用 JavaScript 支持（如果需要）
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        // 加载特定的网站
        webView.loadUrl("http://kaede.site:8000"); // 替换为您的网址

        // 设置 SwipeRefreshLayout 的刷新监听器
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (isWebViewAtTop()) {
                    // 刷新网页
                    webView.reload();
                } else {
                    // 如果没有在顶部，则不执行刷新，并停止刷新动画
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        });

        // 在网页加载完成后隐藏刷新进度条
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                // 停止刷新动画
                swipeRefreshLayout.setRefreshing(false);
            }
        });

        // 监听 WebView 滚动
        webView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                // 检查是否滑动到顶部
                if (scrollY == 0) {
                    swipeRefreshLayout.setEnabled(true);
                } else {
                    swipeRefreshLayout.setEnabled(false);
                }
            }
        });
    }

    private boolean isWebViewAtTop() {
        return webView.getScrollY() == 0;
    }

    @Override
    public void onBackPressed() {
        // 如果 WebView 中有历史记录，则返回到上一页
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}